package cn.ac.cintcm.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.ac.cintcm.Constants;
import cn.ac.cintcm.model.User;
import cn.ac.cintcm.service.UserManager;

public class AuthorityUtil {
	
	private UserManager userManager = null;
	
	public void setUserManager(UserManager um) {
    	this.userManager = um;
    }

	
	/**
	 * 
	 * @param request
	 * @param response
	 * @param id user id 
	 * @return
	 */
	public boolean hasPrivilegeById(HttpServletRequest request, HttpServletResponse response, String pid) {
		boolean value = false;
		String id = request.getRemoteUser();
		User user = userManager.getUserByUsername(id);
		Long userId = new Long(pid);
		if (request.isUserInRole(Constants.DOCTOR_ROLE)) {
			User patient = userManager.getUser(pid);
			//Doctor's patients
			if (user.getPatients().contains(patient)) {
				value = true;
				//Doctor itself
			} else if (user.getId().longValue() == userId) {
				value = true;
			}
			//Administrator
		} else if (request.isUserInRole(Constants.ADMIN_ROLE)) {
			value = true;
		} else {
			//User itself
			if (userId.longValue()==user.getId().longValue()) {
				value = true;
			}
		}
		return value;
		
	}

}
